import os
import threading
from datetime import datetime
from tkinter import Label, Button, Entry, filedialog, ttk
import regex as re
import tkinter as tk

from util.comm.AsyncTask import AsyncTask
from util.comm.cmd_util import wrap_with_try_except
from util.comm.msg_util import msg
from util.comm.notepad import watch_text_temp


class ClassInit():
    def __init__(self):
        super().__init__()

    def frame(self, tab):
        self.tab = tab

        self.menu = ttk.Frame(tab)
        self.menu.pack()

        self.label = Label(self.menu, text="类文件", width=7)
        self.label.grid(row=0, column=1, padx=0, pady=10)

        self.entry = Entry(self.menu, width=50)
        self.entry.grid(row=0, column=2, padx=2, pady=10)

        self.open_button = Button(self.menu, text="选择文件", command=self.open_file)
        self.open_button.grid(row=0, column=3, padx=2, pady=10)

        self.to_label = Label(self.menu, text="to", width=7)
        self.to_label.grid(row=1, column=1, padx=0, pady=10)

        self.to_entry = Entry(self.menu, width=50)
        self.to_entry.grid(row=1, column=2, padx=2, pady=10)

        self.from_label = Label(self.menu, text="from", width=7)
        self.from_label.grid(row=2, column=1, padx=0, pady=10)

        self.from_entry = Entry(self.menu, width=50)
        self.from_entry.grid(row=2, column=2, padx=2, pady=10)

        self.button = Button(self.menu, text="生成代码", command=self.print_entry_sync)
        self.button.grid(row=3, column=2, padx=5, pady=10)

    def open_file(self):
        file_path = filedialog.askopenfilename()
        if file_path:
            file_name = os.path.basename(file_path)
            if file_name.endswith('.java'):
                self.entry.delete(0, tk.END)
                print(f"Selected file: {file_path}")
                self.entry.insert(0, f"{file_name}")
                self.java_path = file_path
                self.class_name = file_name.replace(".java", "")
            else:
                msg("请选择.java文件")

    def print_entry_sync(self):
        if hasattr(self, 'sync_flag') and self.sync_flag == '1':
            msg('正在处理,请勿重复操作')
            return
        self.sync_flag = '1'
        wrap_print_entry = wrap_with_try_except(self.print_entry)
        AsyncTask(threading.Thread(target=wrap_print_entry, args=()), lambda: self.reset_sync()).execute_async()

    def reset_sync(self):
        self.sync_flag = '0'

    def print_entry(self, clipboard=None):
        if hasattr(self, 'label_out'):
            self.label_out.destroy()

        if self.java_path:
            with open(self.java_path, 'r', encoding='utf-8') as f:
                text = f.read()
        pattern = r'(?<=private\s+[A-z]+\s+)\w+\s?;'
        matches = re.findall(pattern, text)

        to_obj = self.to_entry.get()
        from_obj = self.from_entry.get()
        code_text = f'// {self.class_name} {to_obj} = {self.class_name}.tran({from_obj})\n'
        code_text += f'public static {self.class_name} tran(T {from_obj})'
        code_text += "{\n"
        code_text += f'\t{self.class_name} {to_obj} = new {self.class_name}();\n'
        if matches:
            for match in matches:
                field_name = match.replace(";", "")
                Fn = field_name.capitalize()
                code_text += f'\t{to_obj}.set{Fn}({from_obj}.get{Fn}());\n'
        code_text += f'\treturn {to_obj};\n'
        code_text += "}"
        watch_text_temp(code_text)

        self.label_out = Label(self.tab, text="结果：已输出【%s】" % datetime.now())
        self.label_out.pack()



